package com.yy.xshell.process.resultHandler;

import com.alibaba.fastjson2.JSONObject;
import com.yy.xshell.core.ShellContext;
import com.yy.xshell.core.SshCore;
import com.yy.xshell.auth.SessionContext;
import com.yy.xshell.auth.UserSessionInfo;
import com.yy.xshell.process.Handler;
import org.apache.commons.lang.StringUtils;

/**
 * @author wxy
 * @version 1.0
 * @date 2024/8/21 9:59
 */
public class InsertStrHandler extends Handler<ShellContext> {

    @Override
    public ShellContext handler(ShellContext result) {
        String msg = result.getMsg();
        String[] split = msg.split("\\n");
        UserSessionInfo sessionInfo = SessionContext.get();
        String insertStr = SshCore.getInsertStr(sessionInfo.getUserId(), sessionInfo.getSessionKey());
        if(StringUtils.isEmpty(insertStr) || split[split.length-1].startsWith(insertStr)){
            SshCore.setBeforStr(sessionInfo.getUserId(), sessionInfo.getSessionKey(), split[split.length-1]);
            StringBuilder msgBuilder = new StringBuilder();
            //第一次进入,取最后一行的内容
            for(int i =0 ; i < split.length; i++){
                if(StringUtils.isEmpty(split[i])){
                    msgBuilder.append("\n");
                }else {
                    if(i != (split.length - 1)){
                        msgBuilder.append(split[i]);
                        msgBuilder.append("\n");
                    }
                }
            }
            if(StringUtils.isEmpty(insertStr)){
                insertStr = split[split.length - 1];
                SshCore.putSessionInsertStr(sessionInfo, insertStr);
            }else {
                insertStr = split[split.length - 1];
            }

            result.setInsertStr(insertStr);
            result.setMsg(msgBuilder.toString());
        }else {
            SshCore.setBeforStr(sessionInfo.getUserId(), sessionInfo.getSessionKey(), "");
        }
        return result;
    }

    @Override
    public boolean accept(ShellContext command) {
        return true;
    }

    public static void main(String[] args) {
        String test = ",1,2,3,4";
        String[] split = test.split("[,]");
        System.out.println(split);
    }
}
